using System.Collections.Generic;
using System.ComponentModel;
using Blazing.BusinessObjects.Queries;
using System.BusinessObjects.With;
using Blazing.BusinessObjects.Locations;

namespace Blazing.WebFacade
{
    [System.ComponentModel.DataObject]
    public class LocationController
    {
        [DataObjectMethod(DataObjectMethodType.Delete)]
        public void DeleteLocation(Location location)
        {
            Location.Evict(location.ID);
            location = Location.Load(location.ID);
            With.Transaction.Execute(delegate
            {
                location.Delete();
                location.Save();
            });
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Insert)]
        public Location NewLocation(Location location)
        {
            location.Save();
            return location;
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Update)]
        public Location UpdateLocation(Location location)
        {
            Location.Evict(location.ID);
            location.Save();
            return location;
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select)]
        public IList<Location> GetRootLocations()
        {
            return Location.Search(QrySearchRootLocations.Query());
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select)]
        public IList<Location> GetSubLocations(Location location)
        {
            return location.ChildLocations;
        }

        public void recursiveLocation(List<Location> locations, Location parentLocation)
        {
            IList<Location> clocs = parentLocation.ChildLocations;
            locations.Add(parentLocation);

            if (clocs != null)
            {
                foreach (Location cloc in clocs)
                {
                    recursiveLocation(locations, cloc);
                }
            }
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select)]
        public List<Location> GetLocationsRecursive()
        {
            IList<Location> list = null;
            list = GetRootLocations();

            List<Location> retlist = new List<Location>();
            foreach (Location loc in list)
            {
                recursiveLocation(retlist, loc);
            }

            return retlist;
        }
    }
}
